<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'password', 'status',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'status' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 获取用户角色
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }

    /**
     * 检查用户是否具有指定角色
     */
    public function hasRole($role)
    {
        return $this->roles()->where('name', $role)->exists();
    }

    /**
     * 检查用户是否为管理员
     */
    public function isAdmin()
    {
        return $this->hasRole('admin');
    }

    /**
     * 获取用户的操作日志
     */
    public function operationLogs()
    {
        return $this->hasMany(OperationLog::class);
    }

    /**
     * 获取用户的出入库记录
     */
    public function inventoryRecords()
    {
        return $this->hasMany(InventoryRecord::class, 'operator_id');
    }

    /**
     * 获取用户状态文本
     */
    public function getStatusTextAttribute()
    {
        return $this->status ? '启用' : '禁用';
    }

    /**
     * 获取用户角色名称列表
     */
    public function getRoleNamesAttribute()
    {
        return $this->roles->pluck('name')->join(', ');
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
} 